/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package control;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.Gebruiker;
import model.Teacher;
import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 *
 * @author Linda de Haan
 */
public class ManageTeacherController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Session session = SchoolContentManager.sessionFactory.getCurrentSession(); //get the session from the sessionFactory
        Transaction transaction = session.beginTransaction(); //start the transaction
        response.setContentType("text/html;charset=UTF-8");
        HttpSession sessie = request.getSession();
        Teacher teacher = null;

        if (sessie.getAttribute("manageTeacherController").equals("createTeacher")) {
            if (!request.getParameter("email").isEmpty() && !request.getParameter("firstname").isEmpty()
                    && !request.getParameter("lastname").isEmpty()
                    && !request.getParameter("password1").isEmpty()
                    && !request.getParameter("password2").isEmpty()) {

                if (!request.getParameter("password1").equals(request.getParameter("password2"))) {
                    sessie.setAttribute("ctmsg", "<b>The passwords does not match! Please try again.</b>");
                    sessie.setAttribute("contentPage", "/createTeacher.jsp");
                } else if (!checkmail(request.getParameter("email"))) {
                    sessie.setAttribute("ctmsg", "<b>You have enterd a invalid email! Please try again.</b>");
                    sessie.setAttribute("contentPage", "/createTeacher.jsp");
                } else {
                    String getUserSQL = "SELECT g.email FROM gebruiker g WHERE g.email = '" + request.getParameter("email") + "'";
                    ArrayList<Gebruiker> users = (ArrayList) session.createSQLQuery(getUserSQL).list();

                    if (users != null) {
                        teacher = new Teacher();
                        teacher.setEmail(request.getParameter("email").toLowerCase());
                        teacher.setFirstName(request.getParameter("firstname"));
                        teacher.setInsertion(request.getParameter("insertion"));
                        teacher.setLastName(request.getParameter("lastname"));
                        teacher.setPassword(request.getParameter("password1"));

                        if (request.getParameter("isAdmin").equals("1")) {
                            teacher.setIs_admin(true);
                        } else {
                            teacher.setIs_admin(false);
                        }
                        session.save(teacher);

                        sessie.setAttribute("ctmsg", "<b>Teacher '" + request.getParameter("firstname") + request.getParameter("insertion") + request.getParameter("lastname") + "' successfully created!</b>");
                        sessie.removeAttribute("email");
                        sessie.removeAttribute("firstname");
                        sessie.removeAttribute("insertion");
                        sessie.removeAttribute("lastname");
                        sessie.removeAttribute("password1");
                        sessie.removeAttribute("password2");
                    } else {
                        sessie.setAttribute("ctmsg", "<b>This e-mail is already registered! Please try again.</b>");
                    }
                    sessie.setAttribute("contentPage", "createTeacher.jsp");
                }
            } else {
                sessie.setAttribute("ctmsg", "<b>One or more fields are missing! Please try again.</b>");
                sessie.setAttribute("contentPage", "/createTeacher.jsp");
            }
        } else if (sessie.getAttribute("manageTeacherController").equals("editTeacherSelect")) {
            teacher = (Teacher) session.get(Teacher.class, request.getParameter("teacher"));

            if (teacher.getIs_admin()) {
                sessie.setAttribute("isAdmin", "1");
                sessie.removeAttribute("check0");
                sessie.setAttribute("check1", "checked");
            } else {
                sessie.setAttribute("isAdmin", "0");
                sessie.removeAttribute("check1");
                sessie.setAttribute("check0", "checked");
            }

            sessie.removeAttribute("msmsg");
            sessie.setAttribute("ucode", teacher.getuCode());
            sessie.setAttribute("email", teacher.getEmail());
            sessie.setAttribute("firstname", teacher.getFirstName());
            sessie.setAttribute("insertion", teacher.getInsertion());
            sessie.setAttribute("lastname", teacher.getLastName());
            sessie.setAttribute("contentPage", "editTeacher.jsp");
            addHistori(sessie, "/editTeacherSelect.jsp");

        } else if (sessie.getAttribute("manageTeacherController").equals("editTeacher")) {
            if (checkmail(request.getParameter("email"))) {
                teacher = (Teacher) session.get(Teacher.class, request.getParameter("ucode"));
                teacher.setEmail(request.getParameter("email"));
                teacher.setFirstName(request.getParameter("firstname"));
                teacher.setInsertion(request.getParameter("insertion"));
                teacher.setLastName(request.getParameter("lastname"));
                if (request.getParameter("isAdmin").equals("1")) {
                    teacher.setIs_admin(true);
                    sessie.setAttribute("isAdmin", "1");
                    sessie.removeAttribute("check0");
                    sessie.setAttribute("check1", "checked");
                } else {
                    teacher.setIs_admin(false);
                    sessie.setAttribute("isAdmin", "0");
                    sessie.removeAttribute("check1");
                    sessie.setAttribute("check0", "checked");
                }

                session.saveOrUpdate(teacher);

                String tucodeSQL = "SELECT G.ucode FROM Gebruiker G WHERE G.ucode IN (SELECT T.ucode FROM Teacher T) order by G.ucode";
                String tfnameSQL = "SELECT G.firstname FROM Gebruiker G WHERE G.ucode IN (SELECT T.ucode FROM Teacher T) order by G.ucode";
                String tinsertSQL = "SELECT G.insertion FROM Gebruiker G WHERE G.ucode IN (SELECT T.ucode FROM Teacher T) order by G.ucode";
                String tlnameSQL = "SELECT G.lastname FROM Gebruiker G WHERE G.ucode IN (SELECT T.ucode FROM Teacher T) order by G.ucode";

                ArrayList<String> tucode = (ArrayList) session.createSQLQuery(tucodeSQL).list();
                ArrayList<String> tfname = (ArrayList) session.createSQLQuery(tfnameSQL).list();
                ArrayList<String> tinsert = (ArrayList) session.createSQLQuery(tinsertSQL).list();
                ArrayList<String> tlname = (ArrayList) session.createSQLQuery(tlnameSQL).list();

                sessie.setAttribute("ucode", teacher.getuCode());
                sessie.setAttribute("email", teacher.getEmail());
                sessie.setAttribute("firstname", teacher.getFirstName());
                sessie.setAttribute("insertion", teacher.getInsertion());
                sessie.setAttribute("lastname", teacher.getLastName());
                sessie.setAttribute("lenght", tucode.size());
                sessie.setAttribute("tucode", tucode);
                sessie.setAttribute("tfname", tfname);
                sessie.setAttribute("tinsert", tinsert);
                sessie.setAttribute("tlname", tlname);
                sessie.setAttribute("etmsg", "<b>Change Succesful!</b>");
                sessie.setAttribute("contentPage", "editTeacher.jsp");
                addHistori(sessie, "/editTeacherSelect.jsp");
            } else {
                sessie.setAttribute("etmsg", "<b>You have enterd a invalid email! Please try again.</b>");
                sessie.setAttribute("contentPage", "/editTeacher.jsp");
            }
        }
        transaction.commit();
        response.sendRedirect("index");
    }

    public boolean checkmail(String email) {
        //Set the email pattern string
        Pattern p = Pattern.compile(".+@.+\\.[a-z]+");

        //Match the given string with the pattern
        Matcher m = p.matcher(email);

        //check whether match is found 
        boolean matchFound = m.matches();

        if (matchFound) {
            //System.out.println("Valid Email Id.");

            return true;
        } else {
            //System.out.println("Invalid Email Id.");

            return false;
        }
    }

    private void addHistori(HttpSession sessie, Object attribute) {
        List<Object> historie;
        if (sessie.getAttribute("lastpage") == null) {
            historie = new ArrayList();
        } else {
            historie = (ArrayList<Object>) sessie.getAttribute("lastpage");
        }
        System.out.println("terug naar" + attribute);
        historie.add(attribute);

        sessie.setAttribute("lastpage", historie);
    }

    private Object getLast(HttpSession sessie) {
        List<Object> historie = (List<Object>) sessie.getAttribute("lastpage");
        Object re = historie.get(historie.size() - 1);
        historie.remove(re);
        return re;
    }
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">

    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
